{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "NnD5zKlyzyP2"
   },
   "source": [
    "##### Copyright 2020 The OpenFermion Developers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "id": "SN-b6IcWz0kf"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8fbd165dd6a0"
   },
   "source": [
    "# Introduction to OpenFermion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1GvmtMHYz4gw"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://quantumai.google/openfermion/tutorials/intro_to_openfermion\"><img src=\"https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png\" />View on QuantumAI</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/OpenFermion/blob/master/docs/tutorials/intro_to_openfermion.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/OpenFermion/blob/master/docs/tutorials/intro_to_openfermion.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/github_logo_1x.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/OpenFermion/docs/tutorials/intro_to_openfermion.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/download_icon_1x.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "uQc_KhQWz-pC"
   },
   "source": [
    "Note: The examples below must be run sequentially within a section."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "h2BaAlI60Fvs"
   },
   "source": [
    "## Setup\n",
    "\n",
    "Install the OpenFermion package:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5cbe6b680387"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import openfermion\n",
    "except ImportError:\n",
    "    !pip install git+https://github.com/quantumlib/OpenFermion.git@master#egg=openfermion"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b5c5019fb89f"
   },
   "source": [
    "## Initializing the FermionOperator data structure\n",
    "\n",
    "Fermionic systems are often treated in second quantization where arbitrary operators can be expressed using the fermionic creation and annihilation operators, $a^\\dagger_k$ and $a_k$.  The fermionic ladder operators play a similar role to their qubit ladder operator counterparts, $\\sigma^+_k$ and $\\sigma^-_k$ but are distinguished by the canonical fermionic anticommutation relations, $\\{a^\\dagger_i, a^\\dagger_j\\} = \\{a_i, a_j\\} = 0$ and $\\{a_i, a_j^\\dagger\\} = \\delta_{ij}$. Any weighted sums of products of these operators are represented with the FermionOperator data structure in OpenFermion. The following are examples of valid FermionOperators:\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "& a_1 \\nonumber \\\\\n",
    "& 1.7 a^\\dagger_3 \\nonumber \\\\\n",
    "&-1.7 \\, a^\\dagger_3 a_1 \\nonumber \\\\\n",
    "&(1 + 2i) \\, a^\\dagger_4 a^\\dagger_3 a_9 a_1 \\nonumber \\\\\n",
    "&(1 + 2i) \\, a^\\dagger_4 a^\\dagger_3 a_9 a_1 - 1.7 \\, a^\\dagger_3 a_1 \\nonumber\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "The FermionOperator class is contained in $\\textrm{ops/_fermion_operator.py}$. In order to support fast addition of FermionOperator instances, the class is implemented as hash table (python dictionary). The keys of the dictionary encode the strings of ladder operators and values of the dictionary store the coefficients. The strings of ladder operators are encoded as a tuple of 2-tuples which we refer to as the \"terms tuple\". Each ladder operator is represented by a 2-tuple. The first element of the 2-tuple is an int indicating the tensor factor on which the ladder operator acts. The second element of the 2-tuple is Boole: 1 represents raising and 0 represents lowering. For instance, $a^\\dagger_8$ is represented in a 2-tuple as $(8, 1)$. Note that indices start at 0 and the identity operator is an empty list. Below we give some examples of operators and their terms tuple:\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "I & \\mapsto () \\nonumber \\\\\n",
    "a_1 & \\mapsto ((1, 0),) \\nonumber \\\\\n",
    "a^\\dagger_3 & \\mapsto ((3, 1),) \\nonumber \\\\\n",
    "a^\\dagger_3 a_1 & \\mapsto ((3, 1), (1, 0)) \\nonumber \\\\\n",
    "a^\\dagger_4 a^\\dagger_3 a_9 a_1 & \\mapsto ((4, 1), (3, 1), (9, 0), (1, 0)) \\nonumber\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "Note that when initializing a single ladder operator one should be careful to add the comma after the inner pair. This is because in python ((1, 2)) = (1, 2) whereas ((1, 2),) = ((1, 2),). The \"terms tuple\" is usually convenient when one wishes to initialize a term as part of a coded routine. However, the terms tuple is not particularly intuitive. Accordingly, OpenFermion also supports another user-friendly, string notation below. This representation is rendered when calling \"print\" on a FermionOperator.\n",
    "\n",
    "$$\n",
    "\\begin{align}\n",
    "I & \\mapsto \\textrm{\"\"} \\nonumber \\\\\n",
    "a_1 & \\mapsto \\textrm{\"1\"} \\nonumber \\\\\n",
    "a^\\dagger_3 & \\mapsto \\textrm{\"3^\"} \\nonumber \\\\\n",
    "a^\\dagger_3 a_1 & \\mapsto \\textrm{\"3^}\\;\\textrm{1\"} \\nonumber \\\\\n",
    "a^\\dagger_4 a^\\dagger_3 a_9 a_1 & \\mapsto \\textrm{\"4^}\\;\\textrm{3^}\\;\\textrm{9}\\;\\textrm{1\"} \\nonumber\n",
    "\\end{align}\n",
    "$$\n",
    "\n",
    "Let's initialize our first term! We do it two different ways below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "64c2dfa09ecc"
   },
   "outputs": [],
   "source": [
    "from openfermion.ops import FermionOperator\n",
    "\n",
    "my_term = FermionOperator(((3, 1), (1, 0)))\n",
    "print(my_term)\n",
    "\n",
    "my_term = FermionOperator('3^ 1')\n",
    "print(my_term)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "67e045aa5d07"
   },
   "source": [
    "The preferred way to specify the coefficient in openfermion is to provide an optional coefficient argument. If not provided, the coefficient defaults to 1. In the code below, the first method is preferred. The multiplication in the second method actually creates a copy of the term, which introduces some additional cost. All inplace operands (such as +=) modify classes whereas binary operands such as + create copies. Important caveats are that the empty tuple FermionOperator(()) and the empty string FermionOperator('') initializes identity. The empty initializer FermionOperator() initializes the zero operator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "f05e9d9f339c"
   },
   "outputs": [],
   "source": [
    "good_way_to_initialize = FermionOperator('3^ 1', -1.7)\n",
    "print(good_way_to_initialize)\n",
    "\n",
    "bad_way_to_initialize = -1.7 * FermionOperator('3^ 1')\n",
    "print(bad_way_to_initialize)\n",
    "\n",
    "identity = FermionOperator('')\n",
    "print(identity)\n",
    "\n",
    "zero_operator = FermionOperator()\n",
    "print(zero_operator)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "542e18914afa"
   },
   "source": [
    "Note that FermionOperator has only one attribute: .terms. This attribute is the dictionary which stores the term tuples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "4a11312fb80a"
   },
   "outputs": [],
   "source": [
    "my_operator = FermionOperator('4^ 1^ 3 9', 1. + 2.j)\n",
    "print(my_operator)\n",
    "print(my_operator.terms)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a98be7f63fc8"
   },
   "source": [
    "## Manipulating the FermionOperator data structure\n",
    "So far we have explained how to initialize a single FermionOperator such as $-1.7 \\, a^\\dagger_3 a_1$. However, in general we will want to represent sums of these operators such as $(1 + 2i) \\, a^\\dagger_4 a^\\dagger_3 a_9 a_1 - 1.7 \\, a^\\dagger_3 a_1$. To do this, just add together two FermionOperators! We demonstrate below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "7c3a76f7f51b"
   },
   "outputs": [],
   "source": [
    "from openfermion.ops import FermionOperator\n",
    "\n",
    "term_1 = FermionOperator('4^ 3^ 9 1', 1. + 2.j)\n",
    "term_2 = FermionOperator('3^ 1', -1.7)\n",
    "my_operator = term_1 + term_2\n",
    "print(my_operator)\n",
    "\n",
    "my_operator = FermionOperator('4^ 3^ 9 1', 1. + 2.j)\n",
    "term_2 = FermionOperator('3^ 1', -1.7)\n",
    "my_operator += term_2\n",
    "print('')\n",
    "print(my_operator)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9caf5fa5a733"
   },
   "source": [
    "The print function prints each term in the operator on a different line. Note that the line my_operator = term_1 + term_2 creates a new object, which involves a copy of term_1 and term_2. The second block of code uses the inplace method +=, which is more efficient. This is especially important when trying to construct a very large FermionOperator. FermionOperators also support a wide range of builtins including, str(), repr(), ==, !=, *=, *, /, /=, +, +=, -, -=, - and **. Note that since FermionOperators involve floats, == and != check for (in)equality up to numerical precision. We demonstrate some of these methods below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "66bdc1434c35"
   },
   "outputs": [],
   "source": [
    "term_1 = FermionOperator('4^ 3^ 9 1', 1. + 2.j)\n",
    "term_2 = FermionOperator('3^ 1', -1.7)\n",
    "\n",
    "my_operator = term_1 - 33. * term_2\n",
    "print(my_operator)\n",
    "\n",
    "my_operator *= 3.17 * (term_2 + term_1) ** 2\n",
    "print('')\n",
    "print(my_operator)\n",
    "\n",
    "print('')\n",
    "print(term_2 ** 3)\n",
    "\n",
    "print('')\n",
    "print(term_1 == 2.*term_1 - term_1)\n",
    "print(term_1 == my_operator)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "677699404e3f"
   },
   "source": [
    "Additionally, there are a variety of methods that act on the FermionOperator data structure. We demonstrate a small subset of those methods here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "041dd8919981"
   },
   "outputs": [],
   "source": [
    "from openfermion.utils import commutator, count_qubits, hermitian_conjugated\n",
    "from openfermion.transforms import normal_ordered\n",
    "\n",
    "# Get the Hermitian conjugate of a FermionOperator, count its qubit, check if it is normal-ordered.\n",
    "term_1 = FermionOperator('4^ 3 3^', 1. + 2.j)\n",
    "print(hermitian_conjugated(term_1))\n",
    "print(term_1.is_normal_ordered())\n",
    "print(count_qubits(term_1))\n",
    "\n",
    "# Normal order the term.\n",
    "term_2 = normal_ordered(term_1)\n",
    "print('')\n",
    "print(term_2)\n",
    "print(term_2.is_normal_ordered())\n",
    "\n",
    "# Compute a commutator of the terms.\n",
    "print('')\n",
    "print(commutator(term_1, term_2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a77c6c50b363"
   },
   "source": [
    "## The QubitOperator data structure\n",
    "The QubitOperator data structure is another essential part of openfermion. As the name suggests, QubitOperator is used to store qubit operators in almost exactly the same way that FermionOperator is used to store fermion operators. For instance $X_0 Z_3 Y_4$ is a QubitOperator. The internal representation of this as a terms tuple would be $((0, \\textrm{\"X\"}), (3, \\textrm{\"Z\"}), (4, \\textrm{\"Y\"}))$. Note that one important difference between QubitOperator and FermionOperator is that the terms in QubitOperator are always sorted in order of tensor factor. In some cases, this enables faster manipulation. We initialize some QubitOperators below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "7553dbe95a16"
   },
   "outputs": [],
   "source": [
    "from openfermion.ops import QubitOperator\n",
    "\n",
    "my_first_qubit_operator = QubitOperator('X1 Y2 Z3')\n",
    "print(my_first_qubit_operator)\n",
    "print(my_first_qubit_operator.terms)\n",
    "\n",
    "operator_2 = QubitOperator('X3 Z4', 3.17)\n",
    "operator_2 -= 77. * my_first_qubit_operator\n",
    "print('')\n",
    "print(operator_2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "700ab8163a06"
   },
   "source": [
    "## Jordan-Wigner and Bravyi-Kitaev\n",
    "openfermion provides functions for mapping FermionOperators to QubitOperators."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "dba78129ea1a"
   },
   "outputs": [],
   "source": [
    "from openfermion.ops import FermionOperator\n",
    "from openfermion.transforms import jordan_wigner, bravyi_kitaev\n",
    "from openfermion.utils import hermitian_conjugated\n",
    "from openfermion.linalg import eigenspectrum\n",
    "\n",
    "# Initialize an operator.\n",
    "fermion_operator = FermionOperator('2^ 0', 3.17)\n",
    "fermion_operator += hermitian_conjugated(fermion_operator)\n",
    "print(fermion_operator)\n",
    "\n",
    "# Transform to qubits under the Jordan-Wigner transformation and print its spectrum.\n",
    "jw_operator = jordan_wigner(fermion_operator)\n",
    "print('')\n",
    "print(jw_operator)\n",
    "jw_spectrum = eigenspectrum(jw_operator)\n",
    "print(jw_spectrum)\n",
    "\n",
    "# Transform to qubits under the Bravyi-Kitaev transformation and print its spectrum.\n",
    "bk_operator = bravyi_kitaev(fermion_operator)\n",
    "print('')\n",
    "print(bk_operator)\n",
    "bk_spectrum = eigenspectrum(bk_operator)\n",
    "print(bk_spectrum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a16a5035e613"
   },
   "source": [
    "We see that despite the different representation, these operators are iso-spectral. We can also apply the Jordan-Wigner transform in reverse to map arbitrary QubitOperators to FermionOperators. Note that we also demonstrate the .compress() method (a method on both FermionOperators and QubitOperators) which removes zero entries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "3fcd69192461"
   },
   "outputs": [],
   "source": [
    "from openfermion.transforms import reverse_jordan_wigner\n",
    "\n",
    "# Initialize QubitOperator.\n",
    "my_operator = QubitOperator('X0 Y1 Z2', 88.)\n",
    "my_operator += QubitOperator('Z1 Z4', 3.17)\n",
    "print(my_operator)\n",
    "\n",
    "# Map QubitOperator to a FermionOperator.\n",
    "mapped_operator = reverse_jordan_wigner(my_operator)\n",
    "print('')\n",
    "print(mapped_operator)\n",
    "\n",
    "# Map the operator back to qubits and make sure it is the same.\n",
    "back_to_normal = jordan_wigner(mapped_operator)\n",
    "back_to_normal.compress()\n",
    "print('')\n",
    "print(back_to_normal)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "05a8461a9494"
   },
   "source": [
    "## Sparse matrices and the Hubbard model\n",
    "Often, one would like to obtain a sparse matrix representation of an operator which can be analyzed numerically. There is code in both openfermion.transforms and openfermion.utils which facilitates this. The function get_sparse_operator converts either a FermionOperator, a QubitOperator or other more advanced classes such as InteractionOperator to a scipy.sparse.csc matrix. There are numerous functions in openfermion.utils which one can call on the sparse operators such as \"get_gap\", \"get_hartree_fock_state\", \"get_ground_state\", etc. We show this off by computing the ground state energy of the Hubbard model. To do that, we use code from the openfermion.hamiltonians module which constructs lattice models of fermions such as Hubbard models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "856612631b71"
   },
   "outputs": [],
   "source": [
    "from openfermion.hamiltonians import fermi_hubbard\n",
    "from openfermion.linalg import get_sparse_operator, get_ground_state\n",
    "from openfermion.transforms import jordan_wigner\n",
    "\n",
    "\n",
    "# Set model.\n",
    "x_dimension = 2\n",
    "y_dimension = 2\n",
    "tunneling = 2.\n",
    "coulomb = 1.\n",
    "magnetic_field = 0.5\n",
    "chemical_potential = 0.25\n",
    "periodic = 1\n",
    "spinless = 1\n",
    "\n",
    "# Get fermion operator.\n",
    "hubbard_model = fermi_hubbard(\n",
    "    x_dimension, y_dimension, tunneling, coulomb, chemical_potential,\n",
    "    magnetic_field, periodic, spinless)\n",
    "print(hubbard_model)\n",
    "\n",
    "# Get qubit operator under Jordan-Wigner.\n",
    "jw_hamiltonian = jordan_wigner(hubbard_model)\n",
    "jw_hamiltonian.compress()\n",
    "print('')\n",
    "print(jw_hamiltonian)\n",
    "\n",
    "# Get scipy.sparse.csc representation.\n",
    "sparse_operator = get_sparse_operator(hubbard_model)\n",
    "print('')\n",
    "print(sparse_operator)\n",
    "print('\\nEnergy of the model is {} in units of T and J.'.format(\n",
    "    get_ground_state(sparse_operator)[0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "f68bc9ed0386"
   },
   "source": [
    "## Hamiltonians in the plane wave basis\n",
    "A user can write plugins to openfermion which allow for the use of, e.g., third-party electronic structure package to compute molecular orbitals, Hamiltonians, energies, reduced density matrices, coupled cluster amplitudes, etc using Gaussian basis sets. We may provide scripts which interface between such packages and openfermion in future but do not discuss them in this tutorial.\n",
    "\n",
    "When using simpler basis sets such as plane waves, these packages are not needed. openfermion comes with code which computes Hamiltonians in the plane wave basis. Note that when using plane waves, one is working with the periodized Coulomb operator, best suited for condensed phase calculations such as studying the electronic structure of a solid. To obtain these Hamiltonians one must choose to study the system without a spin degree of freedom (spinless), one must the specify dimension in which the calculation is performed (n_dimensions, usually 3), one must specify how many plane waves are in each dimension (grid_length) and one must specify the length scale of the plane wave harmonics in each dimension (length_scale) and also the locations and charges of the nuclei. One can generate these models with plane_wave_hamiltonian() found in openfermion.hamiltonians. For simplicity, below we compute the Hamiltonian in the case of zero external charge (corresponding to the uniform electron gas, aka jellium). We also demonstrate that one can transform the plane wave Hamiltonian using a Fourier transform without effecting the spectrum of the operator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "3233b272c2a8"
   },
   "outputs": [],
   "source": [
    "from openfermion.hamiltonians import jellium_model\n",
    "from openfermion.utils import Grid\n",
    "from openfermion.linalg import eigenspectrum\n",
    "from openfermion.transforms import jordan_wigner, fourier_transform\n",
    "\n",
    "# Let's look at a very small model of jellium in 1D.\n",
    "grid = Grid(dimensions=1, length=3, scale=1.0)\n",
    "spinless = True\n",
    "\n",
    "# Get the momentum Hamiltonian.\n",
    "momentum_hamiltonian = jellium_model(grid, spinless)\n",
    "momentum_qubit_operator = jordan_wigner(momentum_hamiltonian)\n",
    "momentum_qubit_operator.compress()\n",
    "print(momentum_qubit_operator)\n",
    "\n",
    "# Fourier transform the Hamiltonian to the position basis.\n",
    "position_hamiltonian = fourier_transform(momentum_hamiltonian, grid, spinless)\n",
    "position_qubit_operator = jordan_wigner(position_hamiltonian)\n",
    "position_qubit_operator.compress()\n",
    "print('')\n",
    "print (position_qubit_operator)\n",
    "\n",
    "# Check the spectra to make sure these representations are iso-spectral.\n",
    "spectral_difference = eigenspectrum(momentum_qubit_operator) -  eigenspectrum(position_qubit_operator)\n",
    "print('')\n",
    "print(spectral_difference)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "f74d3740b3da"
   },
   "source": [
    "## Basics of MolecularData class\n",
    "\n",
    "Data from electronic structure calculations can be saved in an OpenFermion data structure called MolecularData, which makes it easy to access within our library. Often, one would like to analyze a chemical series or look at many different Hamiltonians and sometimes the electronic structure calculations are either expensive to compute or difficult to converge (e.g. one needs to mess around with different types of SCF routines to make things converge). Accordingly, we anticipate that users will want some way to automatically database the results of their electronic structure calculations so that important data (such as the SCF integrals) can be looked up on-the-fly if the user has computed them in the past. OpenFermion supports a data provenance strategy which saves key results of the electronic structure calculation (including pointers to files containing large amounts of data, such as the molecular integrals) in an HDF5 container.\n",
    "\n",
    "The MolecularData class stores information about molecules. One initializes a MolecularData object by specifying parameters of a molecule such as its geometry, basis, multiplicity, charge and an optional string describing it. One can also initialize MolecularData simply by providing a string giving a filename where a previous MolecularData object was saved in an HDF5 container. One can save a MolecularData instance by calling the class's .save() method. This automatically saves the instance in a data folder specified during OpenFermion installation. The name of the file is generated automatically from the instance attributes and optionally provided description. Alternatively, a filename can also be provided as an optional input if one wishes to manually name the file.\n",
    "\n",
    "When electronic structure calculations are run, the data files for the molecule can be automatically updated. If one wishes to later use that data they either initialize MolecularData with the instance filename or initialize the instance and then later call the .load() method.\n",
    "\n",
    "Basis functions are provided to initialization using a string such as \"6-31g\". Geometries can be specified using a simple txt input file (see geometry_from_file function in molecular_data.py) or can be passed using a simple python list format demonstrated below. Atoms are specified using a string for their atomic symbol. Distances should be provided in angstrom. Below we initialize a simple instance of MolecularData without performing any electronic structure calculations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8f1494b89898"
   },
   "outputs": [],
   "source": [
    "from openfermion.chem import MolecularData\n",
    "\n",
    "# Set parameters to make a simple molecule.\n",
    "diatomic_bond_length = .7414\n",
    "geometry = [('H', (0., 0., 0.)), ('H', (0., 0., diatomic_bond_length))]\n",
    "basis = 'sto-3g'\n",
    "multiplicity = 1\n",
    "charge = 0\n",
    "description = str(diatomic_bond_length)\n",
    "\n",
    "# Make molecule and print out a few interesting facts about it.\n",
    "molecule = MolecularData(geometry, basis, multiplicity,\n",
    "                         charge, description)\n",
    "print('Molecule has automatically generated name {}'.format(\n",
    "    molecule.name))\n",
    "print('Information about this molecule would be saved at:\\n{}\\n'.format(\n",
    "    molecule.filename))\n",
    "print('This molecule has {} atoms and {} electrons.'.format(\n",
    "    molecule.n_atoms, molecule.n_electrons))\n",
    "for atom, atomic_number in zip(molecule.atoms, molecule.protons):\n",
    "    print('Contains {} atom, which has {} protons.'.format(\n",
    "        atom, atomic_number))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ef1b387ad32a"
   },
   "source": [
    "If we had previously computed this molecule using an electronic structure package, we can call molecule.load() to populate all sorts of interesting fields in the data structure. Though we make no assumptions about what electronic structure packages users might install, we assume that the calculations are saved in OpenFermion's MolecularData objects. Currently plugins are available for [Psi4](http://psicode.org/) [(OpenFermion-Psi4)](http://github.com/quantumlib/OpenFermion-Psi4) and [PySCF](https://github.com/sunqm/pyscf) [(OpenFermion-PySCF)](http://github.com/quantumlib/OpenFermion-PySCF), and there may be more in the future. For the purposes of this example, we will load data that ships with OpenFermion to make a plot of the energy surface of hydrogen. Note that helper functions to initialize some interesting chemical benchmarks are found in openfermion.utils."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9e47d329a646"
   },
   "outputs": [],
   "source": [
    "# Set molecule parameters.\n",
    "basis = 'sto-3g'\n",
    "multiplicity = 1\n",
    "bond_length_interval = 0.1\n",
    "n_points = 25\n",
    "\n",
    "# Generate molecule at different bond lengths.\n",
    "hf_energies = []\n",
    "fci_energies = []\n",
    "bond_lengths = []\n",
    "for point in range(3, n_points + 1):\n",
    "    bond_length = bond_length_interval * point\n",
    "    bond_lengths += [bond_length]\n",
    "    description = str(round(bond_length,2))\n",
    "    print(description)\n",
    "    geometry = [('H', (0., 0., 0.)), ('H', (0., 0., bond_length))]\n",
    "    molecule = MolecularData(\n",
    "        geometry, basis, multiplicity, description=description)\n",
    "    \n",
    "    # Load data.\n",
    "    molecule.load()\n",
    "\n",
    "    # Print out some results of calculation.\n",
    "    print('\\nAt bond length of {} angstrom, molecular hydrogen has:'.format(\n",
    "        bond_length))\n",
    "    print('Hartree-Fock energy of {} Hartree.'.format(molecule.hf_energy))\n",
    "    print('MP2 energy of {} Hartree.'.format(molecule.mp2_energy))\n",
    "    print('FCI energy of {} Hartree.'.format(molecule.fci_energy))\n",
    "    print('Nuclear repulsion energy between protons is {} Hartree.'.format(\n",
    "        molecule.nuclear_repulsion))\n",
    "    for orbital in range(molecule.n_orbitals):\n",
    "        print('Spatial orbital {} has energy of {} Hartree.'.format(\n",
    "            orbital, molecule.orbital_energies[orbital]))\n",
    "    hf_energies += [molecule.hf_energy]\n",
    "    fci_energies += [molecule.fci_energy]\n",
    "\n",
    "# Plot.\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "plt.figure(0)\n",
    "plt.plot(bond_lengths, fci_energies, 'x-')\n",
    "plt.plot(bond_lengths, hf_energies, 'o-')\n",
    "plt.ylabel('Energy in Hartree')\n",
    "plt.xlabel('Bond length in angstrom')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0aa06eb285b9"
   },
   "source": [
    "The geometry data needed to generate MolecularData can also be retrieved from the PubChem online database by inputting the molecule's name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "fe2bcf81ef81"
   },
   "outputs": [],
   "source": [
    "from openfermion.chem import geometry_from_pubchem\n",
    "\n",
    "methane_geometry = geometry_from_pubchem('methane')\n",
    "print(methane_geometry)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "e16b7d684cce"
   },
   "source": [
    "## InteractionOperator and InteractionRDM for efficient numerical representations\n",
    "\n",
    "Fermion Hamiltonians can be expressed as $H = h_0 + \\sum_{pq} h_{pq}\\, a^\\dagger_p a_q + \\frac{1}{2} \\sum_{pqrs} h_{pqrs} \\, a^\\dagger_p a^\\dagger_q a_r a_s$ where $h_0$ is a constant shift due to the nuclear repulsion and $h_{pq}$ and $h_{pqrs}$ are the famous molecular integrals. Since fermions interact pairwise, their energy is thus a unique function of the one-particle and two-particle reduced density matrices which are expressed in second quantization as $\\rho_{pq} = \\left \\langle p \\mid a^\\dagger_p a_q \\mid q \\right \\rangle$ and $\\rho_{pqrs} = \\left \\langle pq \\mid a^\\dagger_p a^\\dagger_q a_r a_s \\mid rs \\right \\rangle$, respectively.\n",
    "\n",
    "Because the RDMs and molecular Hamiltonians are both compactly represented and manipulated as 2- and 4- index tensors, we can represent them in a particularly efficient form using  similar data structures. The InteractionOperator data structure can be initialized for a Hamiltonian by passing the constant $h_0$ (or 0), as well as numpy arrays representing $h_{pq}$ (or $\\rho_{pq}$) and $h_{pqrs}$ (or $\\rho_{pqrs}$). Importantly, InteractionOperators can also be obtained by calling MolecularData.get_molecular_hamiltonian() or by calling the function get_interaction_operator() (found in openfermion.transforms) on a FermionOperator. The InteractionRDM data structure is similar but represents RDMs. For instance, one can get a molecular RDM by calling MolecularData.get_molecular_rdm(). When generating Hamiltonians from the MolecularData class, one can choose to restrict the system to an active space.\n",
    "\n",
    "These classes inherit from the same base class, PolynomialTensor. This data structure overloads the slice operator [] so that one can get or set the key attributes of the InteractionOperator: $\\textrm{.constant}$, $\\textrm{.one_body_coefficients}$ and $\\textrm{.two_body_coefficients}$ . For instance, InteractionOperator[(p, 1), (q, 1), (r, 0), (s, 0)] would return $h_{pqrs}$ and InteractionRDM would return $\\rho_{pqrs}$. Importantly, the class supports fast basis transformations using the method PolynomialTensor.rotate_basis(rotation_matrix).\n",
    "But perhaps most importantly, one can map the InteractionOperator to any of the other data structures we've described here.\n",
    "\n",
    "Below, we load MolecularData from a saved calculation of LiH. We then obtain an InteractionOperator representation of this system in an active space. We then map that operator to qubits. We then demonstrate that one can rotate the orbital basis of the InteractionOperator using random angles to obtain a totally different operator that is still iso-spectral."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "bb92dd542ada"
   },
   "outputs": [],
   "source": [
    "from openfermion.chem import MolecularData\n",
    "from openfermion.transforms import get_fermion_operator, jordan_wigner\n",
    "from openfermion.linalg import get_ground_state, get_sparse_operator\n",
    "import numpy\n",
    "import scipy\n",
    "import scipy.linalg\n",
    "\n",
    "# Load saved file for LiH.\n",
    "diatomic_bond_length = 1.45\n",
    "geometry = [('Li', (0., 0., 0.)), ('H', (0., 0., diatomic_bond_length))]\n",
    "basis = 'sto-3g'\n",
    "multiplicity = 1\n",
    "\n",
    "# Set Hamiltonian parameters.\n",
    "active_space_start = 1\n",
    "active_space_stop = 3\n",
    "\n",
    "# Generate and populate instance of MolecularData.\n",
    "molecule = MolecularData(geometry, basis, multiplicity, description=\"1.45\")\n",
    "molecule.load()\n",
    "\n",
    "# Get the Hamiltonian in an active space.\n",
    "molecular_hamiltonian = molecule.get_molecular_hamiltonian(\n",
    "    occupied_indices=range(active_space_start),\n",
    "    active_indices=range(active_space_start, active_space_stop))\n",
    "\n",
    "# Map operator to fermions and qubits.\n",
    "fermion_hamiltonian = get_fermion_operator(molecular_hamiltonian)\n",
    "qubit_hamiltonian = jordan_wigner(fermion_hamiltonian)\n",
    "qubit_hamiltonian.compress()\n",
    "print('The Jordan-Wigner Hamiltonian in canonical basis follows:\\n{}'.format(qubit_hamiltonian))\n",
    "\n",
    "# Get sparse operator and ground state energy.\n",
    "sparse_hamiltonian = get_sparse_operator(qubit_hamiltonian)\n",
    "energy, state = get_ground_state(sparse_hamiltonian)\n",
    "print('Ground state energy before rotation is {} Hartree.\\n'.format(energy))\n",
    "\n",
    "# Randomly rotate.\n",
    "n_orbitals = molecular_hamiltonian.n_qubits // 2\n",
    "n_variables = int(n_orbitals * (n_orbitals - 1) / 2)\n",
    "numpy.random.seed(1)\n",
    "random_angles = numpy.pi * (1. - 2. * numpy.random.rand(n_variables))\n",
    "kappa = numpy.zeros((n_orbitals, n_orbitals))\n",
    "index = 0\n",
    "for p in range(n_orbitals):\n",
    "    for q in range(p + 1, n_orbitals):\n",
    "        kappa[p, q] = random_angles[index]\n",
    "        kappa[q, p] = -numpy.conjugate(random_angles[index])\n",
    "        index += 1\n",
    "\n",
    "    # Build the unitary rotation matrix.\n",
    "    difference_matrix = kappa + kappa.transpose()\n",
    "    rotation_matrix = scipy.linalg.expm(kappa)\n",
    "\n",
    "    # Apply the unitary.\n",
    "    molecular_hamiltonian.rotate_basis(rotation_matrix)\n",
    "\n",
    "# Get qubit Hamiltonian in rotated basis.\n",
    "qubit_hamiltonian = jordan_wigner(molecular_hamiltonian)\n",
    "qubit_hamiltonian.compress()\n",
    "print('The Jordan-Wigner Hamiltonian in rotated basis follows:\\n{}'.format(qubit_hamiltonian))\n",
    "\n",
    "# Get sparse Hamiltonian and energy in rotated basis.\n",
    "sparse_hamiltonian = get_sparse_operator(qubit_hamiltonian)\n",
    "energy, state = get_ground_state(sparse_hamiltonian)\n",
    "print('Ground state energy after rotation is {} Hartree.'.format(energy))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "501889a9bf28"
   },
   "source": [
    "## Quadratic Hamiltonians and Slater determinants\n",
    "\n",
    "The general electronic structure Hamiltonian\n",
    "$H = h_0 + \\sum_{pq} h_{pq}\\, a^\\dagger_p a_q + \\frac{1}{2} \\sum_{pqrs} h_{pqrs} \\, a^\\dagger_p a^\\dagger_q a_r a_s$ contains terms that act on up to 4 sites, or\n",
    "is quartic in the fermionic creation and annihilation operators. However, in many situations\n",
    "we may fruitfully approximate these Hamiltonians by replacing these quartic terms with\n",
    "terms that act on at most 2 fermionic sites, or quadratic terms, as in mean-field approximation theory.  \n",
    "These Hamiltonians have a number of\n",
    "special properties one can exploit for efficient simulation and manipulation of the Hamiltonian, thus\n",
    "warranting a special data structure.  We refer to Hamiltonians which\n",
    "only contain terms that are quadratic in the fermionic creation and annihilation operators\n",
    "as quadratic Hamiltonians, and include the general case of non-particle conserving terms as in\n",
    "a general Bogoliubov transformation.  Eigenstates of quadratic Hamiltonians can be prepared\n",
    "efficiently on both a quantum and classical computer, making them amenable to initial guesses for\n",
    "many more challenging problems.\n",
    "\n",
    "A general quadratic Hamiltonian takes the form\n",
    "$$H = \\sum_{p, q} (M_{pq} - \\mu \\delta_{pq}) a^\\dagger_p a_q + \\frac{1}{2} \\sum_{p, q} (\\Delta_{pq} a^\\dagger_p a^\\dagger_q + \\Delta_{pq}^* a_q a_p) + \\text{constant},$$\n",
    "where $M$ is a Hermitian matrix, $\\Delta$ is an antisymmetric matrix,\n",
    "$\\delta_{pq}$ is the Kronecker delta symbol, and $\\mu$ is a chemical\n",
    "potential term which we keep separate from $M$ so that we can use it\n",
    "to adjust the expectation of the total number of particles.\n",
    "In OpenFermion, quadratic Hamiltonians are conveniently represented and manipulated\n",
    "using the QuadraticHamiltonian class, which stores $M$, $\\Delta$, $\\mu$ and the constant. It is specialized to exploit the properties unique to quadratic Hamiltonians. Like InteractionOperator and InteractionRDM, it inherits from the PolynomialTensor class.\n",
    "\n",
    "The BCS mean-field model of superconductivity is a quadratic Hamiltonian. The following code constructs an instance of this model as a FermionOperator, converts it to a QuadraticHamiltonian, and then computes its ground energy:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "d456cc86d85b"
   },
   "outputs": [],
   "source": [
    "from openfermion.hamiltonians import mean_field_dwave\n",
    "from openfermion.transforms import get_quadratic_hamiltonian\n",
    "\n",
    "# Set model.\n",
    "x_dimension = 2\n",
    "y_dimension = 2\n",
    "tunneling = 2.\n",
    "sc_gap = 1.\n",
    "periodic = True\n",
    "\n",
    "# Get FermionOperator.\n",
    "mean_field_model = mean_field_dwave(\n",
    "    x_dimension, y_dimension, tunneling, sc_gap, periodic=periodic)\n",
    "\n",
    "# Convert to QuadraticHamiltonian\n",
    "quadratic_hamiltonian = get_quadratic_hamiltonian(mean_field_model)\n",
    "\n",
    "# Compute the ground energy\n",
    "ground_energy = quadratic_hamiltonian.ground_energy()\n",
    "print(ground_energy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4e04982c6d75"
   },
   "source": [
    "Any quadratic Hamiltonian may be rewritten in the form\n",
    "$$H = \\sum_p \\varepsilon_p b^\\dagger_p b_p + \\text{constant},$$\n",
    "where the $b_p$ are new annihilation operators that satisfy the fermionic anticommutation relations, and which are linear combinations of the old creation and annihilation operators. This form of $H$ makes it easy to deduce its eigenvalues; they are sums of subsets of the $\\varepsilon_p$, which we call the orbital energies of $H$. The following code computes the orbital energies and the constant:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "89cededb2351"
   },
   "outputs": [],
   "source": [
    "orbital_energies, _, constant = quadratic_hamiltonian.diagonalizing_bogoliubov_transform()\n",
    "print(orbital_energies)\n",
    "print()\n",
    "print(constant)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "7ae7f19c65c4"
   },
   "source": [
    "Eigenstates of quadratic hamiltonians are also known as fermionic Gaussian states, and they can be prepared efficiently on a quantum computer. One can use OpenFermion to obtain circuits for preparing these states. The following code obtains the description of a circuit which prepares the ground state (operations that can be performed in parallel are grouped together), along with a description of the starting state to which the circuit should be applied:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "6adcc984adbb"
   },
   "outputs": [],
   "source": [
    "from openfermion.circuits import gaussian_state_preparation_circuit\n",
    "\n",
    "circuit_description, start_orbitals = gaussian_state_preparation_circuit(quadratic_hamiltonian)\n",
    "for parallel_ops in circuit_description:\n",
    "    print(parallel_ops)\n",
    "print('')\n",
    "print(start_orbitals)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ee3ad12ccb61"
   },
   "source": [
    "In the circuit description, each elementary operation is either a tuple of the form $(i, j, \\theta, \\varphi)$, indicating the operation $\\exp[i \\varphi a_j^\\dagger a_j]\\exp[\\theta (a_i^\\dagger a_j - a_j^\\dagger a_i)]$, which is a Givens rotation of modes $i$ and $j$, or the string 'pht', indicating the particle-hole transformation on the last fermionic mode, which is the operator $\\mathcal{B}$ such that $\\mathcal{B} a_N \\mathcal{B}^\\dagger = a_N^\\dagger$ and leaves the rest of the ladder operators unchanged. Operations that can be performed in parallel are grouped together.\n",
    "\n",
    "In the special case that a quadratic Hamiltonian conserves particle number ($\\Delta = 0$), its eigenstates take the form\n",
    "$$\\lvert \\Psi_S \\rangle = b^\\dagger_{1}\\cdots b^\\dagger_{N_f}\\lvert \\text{vac} \\rangle,\\qquad\n",
    "b^\\dagger_{p} = \\sum_{k=1}^N Q_{pq}a^\\dagger_q,$$\n",
    "where $Q$ is an $N_f \\times N$ matrix with orthonormal rows. These states are also known as Slater determinants. OpenFermion also provides functionality to obtain circuits for preparing Slater determinants starting with the matrix $Q$ as the input."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "intro_to_openfermion.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
